<template>
	<app-layout>
		<search-top ref="search" @search="Search" :searchForm="searchForm">

			<tn-subsection class="tn-border-solid-bottom" @change="setDate" :height="80" mode="button" :borderRadius='0'
				backgroundColor="#fff" :list="datelist"></tn-subsection>
			<tn-tabs @change="setRunType" :current="RunType" :list="RunTypeList" name='title' activeColor="#00aaff"
				flexType="flex-row" inactiveColor="#161616"></tn-tabs>
		</search-top>
		<view v-if="list.length>0" class="nav-height"> </view>
		<view class="list">
			<!-- 工单-->
			<view class="report tn-text-md" v-for="report,index2 in list" :key="index2">

				<view class="">
					<view class="row">
						<view class="value tn-text-bold tn-text-lg">
							工单：{{report['工单编号']}}
						</view>
						<view class="value">
							工序：{{report['工序名称'] }}
						</view>
					</view>
					<view class="row">
						<view class="value">
							部件：{{report['部件名称'] }}
						</view>
						<view class="value">
							品名：{{report['产品名称']}}
						</view>

					</view>
					<view class="row">
						<view class="value">
							工单量：{{report['数量'] || 0}}
						</view>
						<view class="value">
							累计报工：{{report['累计'] || 0}}
						</view>
					</view>
					<view class="row">
						<view class="value" v-if="RunType==0">
							品号：{{report['产品编号'] }}
						</view>
						<view class="value" v-else>
							待生产数量：{{report['待生产数量'] || 0}}
						</view>
						<view class="value ">
							加工类型：{{report['加工类型']}}
						</view>
					</view>
				</view>

				<block v-if="RunType==1">
					<!-- 编辑-->
					<tn-form :labelWidth="150" :model="report" ref="uForm" :errorType="['message']">
						<view class="tn-bg-white ">
							<view class="tn-flex">
								<tn-form-item label="良品数" prop="goodsnum">
									<tn-input v-model="report.goodsnum" type="Number" placeholder="输入良品数量"></tn-input>
								</tn-form-item>
								<tn-form-item label="不良数" prop="badnum">
									<tn-input v-model="report.badnum" type="Number" placeholder="输入不良数"></tn-input>
								</tn-form-item>
							</view>

							<tn-form-item v-if="report.badnum>0" label="不良类型" prop="badtype">
								<tn-input v-model="report.badtype" type="select" :selectOpen="badshow"
									@click="badchange(index2)" placeholder='选择不良类型' />
							</tn-form-item>

							<tn-form-item label="上传图片" prop="jczp">
								<view @click="showloading">
									<tn-image-upload :formData="formData" :action="action" @on-error="uperror"
										@on-remove="removePic(report,$event)" uploadText="" :autoUpload="!!1"
										@on-change="upchange" @on-success="upsuccess($event,report)"
										:showUploadList="setting.showUploadList" :sourceType="setting.sourceType">
									</tn-image-upload>
								</view>
							</tn-form-item>

						</view>
					</tn-form>
				</block>

				<view class="btn">
					<tn-button v-if="RunType==0" fontColor="#fff" @click="start(report)" backgroundColor="#00aa00"
						width="100%" height="70rpx">开始</tn-button>
					<tn-button v-if="RunType==1" backgroundColor="#2074d4" fontColor="#fff" @click="end(report)"
						width="100%" height="70rpx">完成</tn-button>
				</view>
			</view>

		</view>
		<tn-select labelName="不良类型" valueName="序号" v-model="badshow" :list="badlist" @confirm="badconfirm"></tn-select>
		<tn-empty v-if="list.length<1" class="error" icon="/static/error/common.png" mode="data"></tn-empty>

		<view class='tn-tabbar-height'></view>


	</app-layout>
</template>

<script>
	import locationmixin from '@/libs/mixin/location_mixin.js'
	import SearchTop from '@/components/SearchTop'
	import {
		mapGetters,
		mapState
	} from 'vuex';
	export default {
		name: 'REPORT_ADD',
		mixins: [locationmixin],
		components: {
			SearchTop
		},
		computed: {
			...mapState({
				userinfo: state => state.userinfo
			})
		},
		data() {
			return {
				activeIndex: "",
				jgshow: false,
				jglist: [],
				searchForm: {
					work_number: '',
					date_start: '',
					date_end: '',
					name: '',
					procedure: '',
					showgx: 1
				},
				more: false,
				calendar: false,
				datelist: ['全部', '半月内', '一个月内'],
				RunTypeList: [{
					name: '待加工',
					count: ''
				}, {
					name: '加工中',
					count: ''
				}, ],
				RunType: 0,
				formData: {},
				list: [],
				//不良类型
				badshow: false,
				badlist: [],

				form: {
					procedure: '',
					qrcode: '',
					badtype: '',
					bad: '',
				},
				procedureshow: false,
				procedurelist: [],
			}
		},

		onLoad(options) {
			console.log(options)
			let {
				no
			} = options
			if (no) {
				this.searchForm.work_number = no
			}
			this.getList();
		},
		onReady() {
			// this.$refs.uForm.setRules(this.rules)
		},
		onShow() {
			let t = this;
			if (!t.userinfo || !t.userinfo.Fstaffld) {
				t.$user.getInfo()
			}
		},
		onReachBottom() {
			console.log('onReachBottom')
			this.getList();
		},
		watch: {
			'searchForm.work_number': {
				handler(newVal, oldVal) {
					console.log(`属性从${oldVal}变为${newVal}`);
					if (newVal != oldVal) {
						this.$utils.debounce(this.getProcedureList, 1000)
					}
					// 这里可以执行需要的操作
				},
				immediate: true // 如果需要创建时立即触发，则设置immediate为true
			}
		},
		methods: {
			getProcedureList() {
				let that = this;
				return new Promise(reslove => {
					that.$request({
						url: that.$api.procedure.list,
						data: {
							work_number: that.searchForm.work_number,
							Fstaffld: that.userinfo.Fstaffld
						}
					}).then(response => {
						if (response.code === 0) {
							that.procedurelist = response.list
							reslove(response.list)
						}
					}).catch((msg) => {
						this.$t.message.toast(msg);
						this.$t.message.closeLoading();
					});
				})

			},
			procedureconfirm(e) {
				this.searchForm.procedure = [e[0].label];
				this.searchForm.procedurevalue = e[0].label;
				this.$set(this, 'searchForm', this.searchForm)
				console.log('procedureconfirm')
			},
			setRunType(e) {
				console.log(e)
				this.RunType = e;
				this.getList(1)
			},
			setDate(e) {
				this.$refs['search'].setDate(e)
			},

			Search(e) {
				console.log(e)
				this.searchForm = e;
				this.getList(1)
			},

			upsuccess(pic, report) {
				report.pics.push(pic.url)
			},

			removePic(report, idx) {
				report.pics.splice(idx, 1)
			},
			getStatus(report) {
				if (!report['上机时间'] && !report['下机时间']) return 'ready';
				if (report['上机时间']) return 'running';
				if (report['上机时间'] && report['下机时间']) return 'end';
			},
			jgconfirm(e, repoort) {
				repoort.jg = e[0].label;
				repoort.jgtype = e[0].value;
			},
			badchange(idx) {
				this.activeIndex = idx;
				this.badlist = this.list[idx] && this.list[idx]['不良类型'];
				this.badshow = true;
			},
			badconfirm(e, ) {
				this.list[this.activeIndex].bad = e[0].value;
				this.list[this.activeIndex].badtype = e[0].label;
			},

			end(report) {
				let that = this;

				if (!report.goodsnum || !report.badnum) {
					uni.showModal({
						title: '提示',
						content: `您还未上报数量，确认提交工单${report['工单编号']}吗?`,
						success: function(res) {
							if (res.confirm) {
								go()
							}
						}
					});
				} else {
					go();
				}

				function go() {
					that.$t.message.loading("提交中");
					that.$request({
						url: that.$api.worker.edit_end,
						data: {
							// Fstaffld: that.userinfo.Fstaffld,
							pr_id: report['自动编号'],
							gp_num: report.goodsnum || '',
							dp_num: report.badnum || '',
							dp_type: report.badtype || '',
							img: report.pics || [],
						},
						method: "POST",
					}).then(response => {
						that.$t.message.closeLoading();
						console.log(response)
						uni.showModal({
							title: '提示',
							content: response.msg || '操作成功',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									that.getList(1)
									console.log('用户点击确定');
								}
							}
						});
					}).catch((msg) => {
						that.$t.message.toast(msg);
						that.$t.message.closeLoading();
					});
				}
			},

			start(report) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认工单开始吗?',
					success: function(res) {
						if (res.confirm) {
							that.Gostart(report)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			Gostart(report) {
				let that = this;
				that.$t.message.loading("提交中");
				that.$request({
					url: that.$api.worker.edit_start,
					data: {
						Fstaffld: that.userinfo.Fstaffld,
						work_number: report['工单编号'],
						pt_name: report['产品名称'],
						c_name: report['部件名称'],
						pe_name: report['工序名称'],
						p_type: report['加工类型'] || '',
						p_num: report['数量'] || 0,
						a_num: report['累计'] || 0,

					},
					method: "POST",
				}).then(response => {
					that.$t.message.closeLoading();
					console.log(response)
					uni.showModal({
						title: '提示',
						content: response.msg || '操作成功',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								that.getList(1)
								console.log('用户点击确定');
							}
						}
					});
				}).catch((msg) => {
					that.$t.message.toast(msg);
					that.$t.message.closeLoading();
				});
			},

			async getList(issearch = 0) {
				let that = this;
				await this.getProcedureList()
				if (!that.searchForm.procedure || !that.searchForm.procedure.length) {
					that.searchForm.procedure = that.procedurelist.map(e => e['工序名称'])
				}
				that.$t.message.loading("加载中");
				if (issearch) that.page = 1, that.list = [];
				that.$request({
					url: that.$api.worker.getListBg,
					data: {
						limit_page: that.page,
						limit_count: 10,
						Fstaffld: that.userinfo.Fstaffld,
						type: that.RunType,
						...that.searchForm,

					}
				}).then(response => {
					that.$t.message.closeLoading();
					if (response.code === 0) {
						let reslist = [];
						if (response.list.length > 0) {
							response.list.forEach(e => {
								reslist.push({
									pics: [],
									...e,
									...that.$t.deepClone(that.form)
								})
							})
						}
						if (that.page !== 1) {
							that.list = that.list.concat(reslist);
						} else {
							that.list = reslist;
						}
						that.RunTypeList.forEach((type, idx) => {
							type.count = idx == that.RunType ? response.count : 0
						})
					}

				}).catch((msg) => {
					that.$t.message.toast(msg);
					that.$t.message.closeLoading();
				});
			},





		}
	}
</script>

<style lang="scss" scoped>
	.list {
		margin-top: 200upx;
	}

	.nav-height {
		height: 80upx;
	}

	.report {
		background: #fff;
		padding: 20upx;
		border: 1upx solid #eee;
		margin: 10upx;
		border-radius: 10upx;
		box-shadow: 1px 1px 0px 0px #aba7a7;
		position: relative;

		.status {

			display: flex;
			min-width: 150upx;
			align-items: center;
			justify-content: center;
			color: #fff;
			position: absolute;
			right: 0;
			top: 20upx;
			padding: 10upx 0;
			border-top-left-radius: 25upx;
			border-bottom-left-radius: 25upx;
			// transform: rotate(45deg);
			// clip-path: polygon(15px 0, 100% 0, 100% calc(100% - 15px), calc(100% - 15px) 100%, 0 100%, 0 15px);


		}

		.btn {
			padding-top: 20upx;
		}

		.row {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10upx 0;
		}

		.value {
			min-width: 50%;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.tn-form-item {
			padding: 0;
		}
	}

	.right {
		width: 32%;
		display: flex;
		justify-content: space-evenly;
		align-content: center;
		flex-wrap: wrap;

		.more {
			font-size: 40upx;
			display: flex;
			align-items: center;
		}
	}

	.userinfo {
		display: flex;
		font-size: 26upx;
		align-items: center;
		padding: 0 10px;
	}

	.search {
		background-color: #fff;
		padding: 10px;



		.search-btn {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-top: 20upx;
			border-top: 2px solid #eee;
		}
	}

	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
		height: calc(140rpx + constant(safe-area-inset-bottom));
	}
</style>